const { observable, action, runInAction } = require('mobx-miniprogram');
const cloudHelper = require('../../../helpers/cloud_helper.js');
const pageHelper = require('../../../helpers/page_helper.js');

/**
 * 通讯录状态管理
 */
const contactStore = observable({
    // 状态数据
    contactList: [],
    departments: [],
    totalCount: 0,
    currentDept: '',
    activeLetter: '',
    loading: false,
    
    // 搜索相关
    search: '',
    searchResult: [],
    isSearch: false,

    // 加载通讯录数据
    loadContactList: action(async function() {
        try {
            runInAction(() => {
                this.loading = true;
            });
            
            const result = await cloudHelper.callCloudData('home/contact_list', {});
            
            // 获取数据数组
            let contactList = result.data || [];
            
            // 防止null值导致的错误
            if (!Array.isArray(contactList)) {
                contactList = [];
            }
            
            // 过滤掉没有人员的部门
            contactList = contactList.filter(dept => dept.users && dept.users.length > 0);
            
            // 按部门名称排序
            contactList.sort((a, b) => {
                if (a.dept < b.dept) return -1;
                if (a.dept > b.dept) return 1;
                return 0;
            });
            
            // 提取部门列表
            const departments = contactList.map(dept => dept.dept);
            
            // 计算总人数
            const totalCount = contactList.reduce((sum, dept) => sum + dept.users.length, 0);
            
            // 更新状态
            runInAction(() => {
                this.contactList = contactList;
                this.departments = departments;
                this.totalCount = totalCount;
                
                // 如果当前选中的部门已经没有人员，则重置为全部
                if (!contactList.some(dept => dept.dept === this.currentDept)) {
                    this.currentDept = '';
                }
            });
            
            return contactList;
        } catch (error) {
            console.error('加载通讯录失败：', error);
            pageHelper.showModal('加载通讯录失败，请重试');
            
            // 重置状态
            runInAction(() => {
                this.contactList = [];
                this.departments = [];
                this.totalCount = 0;
                this.currentDept = '';
            });
            
            return [];
        } finally {
            runInAction(() => {
                this.loading = false;
            });
        }
    }),
    
    // 设置当前部门
    setCurrentDept: action(function(dept) {
        this.currentDept = dept;
    }),
    
    // 设置活动的字母索引
    setActiveLetter: action(function(letter) {
        this.activeLetter = letter;
    }),
    
    // 处理搜索
    search: action(function(searchText) {
        this.search = searchText;
        
        if (!searchText) {
            this.isSearch = false;
            this.searchResult = [];
            return;
        }
        
        this.isSearch = true;
        
        // 扁平化所有联系人
        let allContacts = [];
        this.contactList.forEach(dept => {
            dept.users.forEach(user => {
                allContacts.push({
                    ...user,
                    deptName: dept.dept
                });
            });
        });
        
        // 搜索匹配
        this.searchResult = allContacts.filter(contact => {
            return contact.name.includes(searchText) || 
                   (contact.mobile && contact.mobile.includes(searchText)) ||
                   (contact.deptName && contact.deptName.includes(searchText));
        });
    }),
    
    // 清除搜索
    clearSearch: action(function() {
        this.search = '';
        this.isSearch = false;
        this.searchResult = [];
    })
});

module.exports = {
    contactStore
}; 